<template>
  <el-form :model="addForm" label-width="120px" class="station-form">
    <el-row :gutter="20">
      <!-- 站点基本信息 -->
      <el-col :span="12">
        <el-form-item label="站点名称">
          <el-input v-model="addForm.stationName"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="站点代码">
          <el-input v-model="addForm.stationCode"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="站点类型">
          <el-input v-model="addForm.stationType"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="站点属性">
          <el-input v-model="addForm.stationProperty"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="18">
        <el-form-item label="详细地址">
          <el-input v-model="addForm.address"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="充电桩数量">
          <el-input-number :model-value="addForm.chargingPiles.length" disabled></el-input-number>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="开店时间">
          <el-time-picker
              v-model="addForm.openTime"
              placeholder="请选择开门时间"
              value-format="HH:mm:ss"
          ></el-time-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="运营状态">
          <el-radio-group v-model="addForm.status">
            <el-radio label="正常">正常</el-radio>
            <el-radio label="已下线">已下线</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="关店时间">
          <el-time-picker
              v-model="addForm.closeTime"
              placeholder="请选择关门时间"
              value-format="HH:mm:ss"
          ></el-time-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="店面是否开启评价" label-width="175">
          <el-switch
              v-model="addForm.enableEvaluation"
              active-text="是"
              inactive-text="否"
              width="45"
          ></el-switch>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-form-item label="电站简介">
          <v-md-editor
              v-model="addForm.stationIntro"
              height="400px"
              placeholder="请输入简介的 Markdown 内容"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="电站图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/upload/images"
              :file-list="addFileList"
              list-type="picture-card"
              :limit="1"
              :auto-upload="true"
              :on-success="handleUploadSuccess"
              :on-remove="handleUploadRemove"
              :on-exceed="handleExceed"
          >
            <i v-if="addFileList.length === 0" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 充电桩列表 -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="充电桩列表">
          <el-table :data="addForm.chargingPiles" style="width: 100%" border>
            <el-table-column prop="pileName" label="充电桩名称"/>
            <el-table-column prop="pileCode" label="充电桩编号"/>
            <el-table-column prop="pileType" label="类型"/>
            <el-table-column prop="pilePower" label="功率 (kW)"/>
            <el-table-column prop="suitableVehicle" label="适合车型"/>
            <el-table-column prop="pileModel" label="型号"/>
            <el-table-column prop="pileDesc" label="描述"/>
            <el-table-column label="操作">
              <template #default="{ row, $index }">
                <el-button size="small" @click="openPileDialog(row)">编辑</el-button>
                <el-button size="small" type="danger"
                           @click="removePile(addForm.chargingPiles, $index)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="openPileDialog()">新增充电桩</el-button>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 底部按钮 -->
    <div style="text-align: right; margin-top: 15px;">
      <el-button @click="cancelDialog">取消</el-button>
      <el-button type="primary" @click="doSave">保存</el-button>
    </div>
  </el-form>

  <!-- 子弹窗：新增/编辑充电桩 -->
  <el-dialog v-model="pileDialogVisible" title="新增/编辑充电桩">
    <el-form :model="pileForm" label-width="120px">
      <el-form-item label="充电桩名称">
        <el-input v-model="pileForm.pileName"></el-input>
      </el-form-item>
      <el-form-item label="充电桩编号">
        <!-- 新增时可编辑，编辑时可禁用 -->
        <el-input v-model="pileForm.pileCode" :disabled="!isAddingPile"></el-input>
      </el-form-item>
      <el-form-item label="类型">
        <el-input v-model="pileForm.pileType"></el-input>
      </el-form-item>
      <el-form-item label="功率 (kW)">
        <el-input-number v-model="pileForm.pilePower"></el-input-number>
      </el-form-item>
      <el-form-item label="型号">
        <el-input v-model="pileForm.pileModel"></el-input>
      </el-form-item>
      <el-form-item label="适合车型">
        <el-input v-model="pileForm.suitableVehicle"></el-input>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="pileForm.pileDesc"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="savePile(addForm.chargingPiles)">保存</el-button>
        <el-button @click="pileDialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import {ref, reactive, watch} from 'vue';
import {ElMessage} from 'element-plus';
import {stationUsePileForm} from '../composables/StationUsePileForm.js';
import axios from 'axios';

export default {
  name: 'StationAddForm',
  emits: ['close', 'refresh'],
  setup(props, {emit}) {
    const {
      openPileDialog,
      pileDialogVisible,
      savePile,
      removePile,
      pileForm,
      isAddingPile
    } = stationUsePileForm();

    const addFileList = ref([]);

    const addForm = reactive({
      stationName: "",
      stationCode: "",
      stationType: "",
      stationProperty: "",
      enableEvaluation: 1,
      openTime: null,
      closeTime: null,
      address: "",
      stationIntro: "",
      stationImgUrl: "",
      createTime: new Date(),
      status: "正常",
      chargingPileCount: 0,
      chargingPiles: [],
    });

    watch(
        () => addForm.chargingPiles,
        (newPiles) => {
          addForm.chargingPileCount = newPiles.length;
        },
        {deep: true}
    );

    // 上传
    const handleUploadRemove = () => {
      addFileList.value = [];
      addForm.stationImgUrl = "";
    };
    const handleExceed = () => {
      ElMessage.error("只能上传一张图片");
    };
    const handleUploadSuccess = (response) => {
      console.log("response: ", response);
      if (typeof response === 'string') {
        // 后端返回纯文本 URL
        addForm.stationImgUrl = response.trim();
        ElMessage.success("图片上传成功");
      } else if (response && response.url) {
        // 后端返回 JSON 格式
        addForm.stationImgUrl = response.url;
        ElMessage.success("图片上传成功");
      } else {
        ElMessage.error("上传失败，未返回图片 URL");
      }
    };

    // 取消
    const cancelDialog = () => {
      emit('close');
    };

    // 保存
    const doSave = async () => {
      if (!addForm.stationName.trim() || !addForm.stationCode.trim()) {
        ElMessage.error("请完善站点信息");
        return;
      }

      addForm.enableEvaluation = addForm.enableEvaluation ? 1 : 0;
      addForm.chargingPileCount = addForm.chargingPiles.length;

      try {
        await axios.post("/station/createStationWithChargingPiles", {
          station: {...addForm},
          chargingPiles: addForm.chargingPiles,
        });
        ElMessage.success("新增成功");
        emit('refresh'); // 刷新列表
        emit('close');   // 关闭弹窗
      } catch (error) {
        ElMessage.error("新增失败");
      }
    };

    return {
      addForm,
      addFileList,
      handleUploadRemove,
      handleExceed,
      handleUploadSuccess,
      doSave,
      cancelDialog,

      // 充电桩
      openPileDialog,
      pileDialogVisible,
      pileForm,
      savePile,
      removePile,
      isAddingPile,
    };
  },
};
</script>

<style scoped>
.station-form {
  padding-bottom: 20px;
}
</style>
